﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using FinPlusDBConn;
using FinPlusCommon;
using u = FinPlusUtility.Utility;

namespace FinPlusComponents
{
    public class FinPlusConnectDB : FinPlusComponent
    {
        public override string[] TestStates { get { return new string[] { "TestString", "IsValid" }; } }
        public override IFunctions Adaptor { get { return _functions; } }
        public override string TestString { get { return Adaptor.ToString(); } }

        private readonly IFinPlusQuery _query;
        private readonly IFunctions _functions;
        private readonly IFinPlusDBConn _conn;
        private readonly ConType _conType;

        //construct
        public FinPlusConnectDB(string group, string where, string queryType, string dateTime, string conType)
        {
            _conn = new FinPlusConn();
            _conType = u.EnumParse<ConType>(conType, ConType.All);
            var type = u.EnumParse<QueryType>(queryType, QueryType.Select);

            switch (type)
            {
                case QueryType.SaveFunc: _query = _conn.SaveFunc(group, where, ConType.NewAndAmend); break;
                case QueryType.Select: _query = _conn.Select(group, where, ConType.NewAndAmend); break;
                case QueryType.SelectAsOf: _query = _conn.SelectAsOf(group, u.ParseDateTime(dateTime), where, _conType); break;
                case QueryType.SelectFrom: _query = _conn.SelectFrom(group, u.ParseDateTime(dateTime), where, _conType); break;
            }

            _functions = _query.Functions;
            _functions.FuncUpdate += Item_Update;

            IsValid = true;
        }

        public FinPlusConnectDB(string xmlPath)
        {
            _functions = new Functions(xmlPath);

            IsValid = true;
        }

        //common control interface
        public override void Dispose()
        {
            if (_query != null)
                _query.Dispose();

            if (_conn != null)
                _conn.Dispose();
        }

        //public
        public void Save(IFunction func)
        {
            if (_conn != null && func != null)
                _conn.Save(func);
        }

        //private
        private void Item_Update(object s, ItemEventArgs a)
        {
            var func = (Function)s;
            
            //TODO REMOVE TEMP KEEP DB SMALL
            if (!func.Name.Equals("Audit")) return;

            if (_conn != null ) _conn.Save(func);
        }
    }
}
